<template>
    <div class="bg-gray-100 flex-1">
        <!-- 右侧内容区域 -->
        <div class="flex-1 p-4">
            <!-- 标题和搜索框 -->
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-3xl font-semibold">科室管理</h2>
            </div>
            <!-- 科室管理表格 -->
            <div class="bg-white p-2 rounded-lg shadow-md mx-auto">
                <var-tabs indicator-color="#006263" active-color="#006263" v-model:active="activeTab">
                    <var-tab>有效</var-tab>
                    <var-tab>已禁用</var-tab>
                </var-tabs>
                <div class="max-h-[528px] overflow-y-auto relative">
                <table class="min-w-full">
                    <thead>
                        <tr>
                            <th  v-for="header in headers" :key="header" class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">
                                {{ header }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="listLoading">
                            <td colspan="6" class="px-6 py-1.4 text-center text-base text-gray-500">
                                <var-loading description="LOADING" color="#006263" />
                            </td>
                        </tr>
                        <tr v-if="list.length === 0 && !listLoading">
                            <td colspan="6" class="px-6 py-1.4 text-center text-base text-gray-500">暂无数据</td>
                        </tr>
                        <tr v-for="(record, departmentId) in list" :key="departmentId" class="odd:bg-white even: bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                            <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-900">{{ record.departmentName || '-' }}</td>
                            <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-500">{{ record.directorName || '-' }}</td>
                            <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-500">{{ formatDate(record.createdAt) }}</td>
                            <!--联系信息列-->
                            <td class="px-2 py-1 whitespace-nowrap text-center text-base">
                                <div class="flex flex-col items-center justify-center">
                                    <var-space :size="[10, 10]">
                                        <var-button block color="#006263" text-color="white" @click="viewContactInfo(record)" class="w-24" style="border-radius: 8px">编 辑</var-button>
                                    </var-space>
                                </div>
                            </td>
                            <!--成员信息列-->
                            <td class="px-2 py-1 whitespace-nowrap text-center text-base">
                                <div class="flex flex-col items-center justify-center">
                                    <var-space :size="[10, 10]">
                                        <var-button block color="#006263" text-color="white" @click="viewMemberInfo(record)" class="w-24" style="border-radius: 8px">查 看</var-button>
                                    </var-space>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
                </div>
                <!-- 分页组件 -->
                <div class="flex justify-center mt-6">
                    <var-pagination v-model="currentPage" v-model:size="pageSize" :total="total" :size-option="[10, 20, 30]" :simple="true" :page-size="pageSize" @change="get" style="color: #006263" />
                </div>
            </div>
        </div>
        <!-- 修改信息弹窗 -->
        <var-popup class="p-9 w-[400px] h-[300px] bg-white rounded-lg shadow-lg" v-model:show="showContactPopup">
            <p class="text-lg mt-4">科室名称：{{ selectedRecord.departmentName }}</p>
            <p class="text-lg mt-4">科室创建者：{{ selectedRecord.createdName }}</p>
            <p class="text-lg mt-4">科室负责人：{{ selectedRecord.directorName }}</p>
            <p class="text-lg mt-4">创建时间：{{ formatDate(selectedRecord.createdAt) }}</p>
            <div class="mt-6 flex justify-center">
                <var-space :size="[10, 30]">
                    <var-button color="#006263" text-color="white" @click="showUpdateDepartment(selectedRecord.departmentName)">修改科室名称</var-button>
                    <var-button v-if="selectedRecord.validFlag === '1'" type="danger" @click="showConfirm = true">删除科室</var-button>
                    <var-button v-if="selectedRecord.validFlag === '0'" type="success" @click="showRecoverConfirm = true">恢复科室</var-button>
                </var-space>
            </div>
        </var-popup>
        <!-- 修改科室名称弹窗 -->
        <var-dialog v-model:show="showUpdate" title="修改科室名称" confirm-button-text-color="#006263" persistent cancel-button-text-color="#006263" width="30vw" @before-close="handleBeforeClose">
            <var-loading description="LOADING" color="#006263" :loading="newDepartmentLoading">
                <div class="p-4">
                    <var-input v-model="newDepartment" variant="outlined" placeholder="请输入修改的科室名称（格式：xx医院xx科室）" focus-color="#006263" size="small" :rules="departmentRules" />
                </div>
            </var-loading>
        </var-dialog>
        <!-- 删除信息确认弹窗 -->
        <var-dialog v-model:show="showConfirm" title="删除科室后科室成员也将踢出该科室且无法恢复，请确认是否继续！" confirm-button-text-color="red" persistent cancel-button-text-color="#006263" width="35vw" @before-close="deleteDepartment">
            <var-loading description="LOADING" color="red" :loading="deleteLoading">
                <div class="p-4">
                    <p class="text-lg text-red-500">确认删除{{ selectedRecord.departmentName }}？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <!--恢复信息确认弹窗  -->
        <var-dialog v-model:show="showRecoverConfirm" title="恢复科室后科室将可正常使用，请确认是否继续！" confirm-button-text-color="green" persistent cancel-button-text-color="#006263" width="35vw" @before-close="recoverDepartment">
            <var-loading description="LOADING" color="green" :loading="recoverLoading">
                <div class="p-4">
                    <p class="text-lg text-green-500">确认恢复{{ selectedRecord.departmentName }}？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <!-- 成员信息弹窗 -->
        <var-popup class="p-6 w-[800px] h-[400px] bg-white shadow-lg rounded-lg" v-model:show="showMemberPopup">
            <p class="text-lg mt-2 mb-2">科室名称：{{ selectedRecord.departmentName }}</p>
            <table class="min-w-full">
                <thead>
                    <tr class="bg-gray-50">
                        <th v-for="header in memberHeaders" :key="header" class="text-center text-base font-medium text-gray-500">
                            {{ header }}
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="members.length === 0">
                        <td colspan="4" class="px-6 py-1.4 whitespace-nowrap text-center text-base text-gray-500">暂无数据</td>
                    </tr>
                    <tr v-for="(member, userId) in members" :key="userId" class="odd:bg-gray-50 even:bg-white" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                        <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-900">{{ member.name }}</td>
                        <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-500">
                            <p v-if="member.directorFlag === '1'" class="text-[#006263]">科室主任</p>
                            <p v-else>成员</p>
                        </td>
                        <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-500">{{ member.sex }}</td>
                        <td class="px-2 py-1 whitespace-nowrap text-center text-base text-gray-500">{{ member.phone }}</td>
                        <td class="px-2 py-1 whitespace-nowrap text-center text-base">
                            <div class="flex flex-col items-center justify-center">
                                <var-space :size="[10, 10]">
                                    <var-button block color="#006263" text-color="white" @click="showUpdateMember(member)" style="border-radius: 8px">编 辑</var-button>
                                </var-space>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </var-popup>
        <!-- 成员信息修改弹窗 -->
        <var-popup class="p-9 w-[480px] h-[540px] bg-white rounded-lg shadow-lg" v-model:show="showUpdateMemberPopup">
            <var-loading description="LOADING" color="#006263" :loading="updateMemberLoading">
                <div class="w-[90%] h-[200px] mx-auto">
                    <var-swipe class="w-full h-full" navigation="hover">
                        <var-swipe-item>
                            <img class="w-full h-full object-cover" :src="selectedMember.imgUrl" />
                        </var-swipe-item>
                    </var-swipe>
                    <div class="text-lg mt-6">姓名: {{ selectedMember.name }}</div>
                    <div class="text-lg mt-2">身份: {{ selectedMember.identity }}</div>
                    <div class="text-lg mt-2">性别：{{ selectedMember.sex }}</div>
                    <div class="text-lg mt-2">电话：{{ selectedMember.phone }}</div>
                    <div class="text-lg mt-2">邮箱: {{ selectedMember.email }}</div>
                    <div class="mt-6 flex justify-center">
                        <var-space :size="[10, 30]">
                            <var-button v-if="selectedMember.directorFlag === '0'" type="success" text-color="white" @click="setDirector">设为主任</var-button>
                            <var-button v-if="selectedMember.directorFlag === '0'" type="danger" text-color="white" @click="delMember">移除该成员</var-button>
                            <p v-if="selectedMember.directorFlag === '1'" class="text-red-500">要对主任进行操作，请先转让主任权限！</p>
                        </var-space>
                    </div>
                </div>
            </var-loading>
        </var-popup>
    </div>
</template>

<script>
import dayjs from 'dayjs';
export default {
    name: 'department',
    data() {
        // 初始化组件数据
        return {
            headers: ['科室名称', '科室负责人', '创建时间', '操作', '查看成员'],
            memberHeaders: ['名字', '职位',  '性别', '电话号码', '操作'],
            activeTab: 0, // 当前激活的选项卡
            list: [],
            members: [], // 成员列表
            total: 0, // 总记录数
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的记录数
            showContactPopup: false, // 控制信息弹窗显示
            showMemberPopup: false, // 控制成员信息弹窗显示
            selectedRecord: {}, // 当前选中的记录
            showUpdate: false, // 控制修改科室名称弹窗显示
            newDepartment: '', // 新科室名称
            showConfirm: false, // 控制信息确认弹窗显示
            showRecoverConfirm: false, // 控制恢复信息确认弹窗显示
            selectedMember: {}, // 当前选中的成员
            showUpdateMemberPopup: false, // 控制成员信息修改弹窗显示
            listLoading: false,
            deleteLoading: false,
            newDepartmentLoading: false,
            recoverLoading: false,
            updateMemberLoading: false
        };
    },
    mounted() {
        // 组件挂载后获取科室列表数据
        this.fetchData();
    },
    watch: {
        activeTab(newVal, oldVal) {
            // 监听 activeTab 变化，当选项卡切换时重新获取数据
            if (newVal !== oldVal) {
                this.currentPage = 1;
                this.fetchData();
            }
        }
    },
    computed: {
        departmentRules() {
            // 计算科室名称输入框的验证规则
            return [(v) => !!v || '科室名称不能为空', (v) => /^.+医院.+科室$/.test(v) || '格式不正确，请输入 xx医院xx科室'];
        }
    },
    methods: {
        formatDate(date) {
            // 格式化日期时间
            return dayjs(date).format('YYYY年MM月DD日 HH:mm');
        },
        async fetchData() {
            // 获取科室列表数据
            this.list = [];
            const typeMap = [1, 0];
            const type = typeMap[this.activeTab];
            this.listLoading = true;
            const res = await this.$api.department.getAdminDepartments({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                type: type
            });
            this.listLoading = false;
            if (res.success) {
                this.list = res.data.list;
                this.total = res.data.total || 0;
            } else {
                console.log(res);
                this.$api.notify.error(res.error);
            }
        },
        get(page, pageSize) {
            // 分页跳转
            if (page !== this.currentPage) {
                this.currentPage = page;
                this.fetchData();
            }
            if (this.pageSize !== pageSize) {
                this.pageSize = pageSize;
                this.currentPage = 1; // 切换分页大小时重置到第一页
                this.fetchData();
            }
        },
        showUpdateDepartment(departmentName) {
            // 显示修改科室名称弹窗
            this.newDepartment = departmentName;
            this.showUpdate = true;
        },
        async handleBeforeClose(action, done) {
            // 处理修改科室名称弹窗的关闭前逻辑
            if (action === 'confirm') {
                if (!this.newDepartment) {
                    this.$api.notify.error('科室名称不能为空！');
                    return;
                }
                this.newDepartmentLoading = true;
                const res = await this.$api.department.adminUpdateDepartment({
                    name: this.newDepartment,
                    departmentId: this.selectedRecord.departmentId
                });
                this.newDepartmentLoading = false;
                if (res.success) {
                    this.$api.notify.success('修改科室名称成功！');
                    this.showUpdate = false;
                    this.showContactPopup = false;
                    this.fetchData();
                } else {
                    this.$api.notify.error(res.error);
                }
            }
            done();
        },
        async deleteDepartment(action, done) {
            // 处理删除科室确认弹窗的关闭前逻辑
            if (action === 'confirm') {
                this.deleteLoading = true;
                const res = await this.$api.department.adminUpdateDepartment({
                    departmentId: this.selectedRecord.departmentId,
                    validFlag: 0
                });
                this.deleteLoading = false;
                if (res.success) {
                    this.$api.notify.success('删除科室成功！');
                    this.showConfirm = false;
                    this.showContactPopup = false;
                    this.fetchData();
                } else {
                    this.$api.notify.error(res.error);
                }
            }
            done();
        },
        async recoverDepartment(action, done) {
            // 处理恢复科室确认弹窗的关闭前逻辑
            if (action === 'confirm') {
                this.recoverLoading = true;
                const res = await this.$api.department.adminUpdateDepartment({
                    departmentId: this.selectedRecord.departmentId,
                    validFlag: 1
                });
                this.recoverLoading = false;
                if (res.success) {
                    this.$api.notify.success('恢复科室成功！');
                    this.showRecoverConfirm = false;
                    this.showContactPopup = false;
                    this.fetchData();
                } else {
                    this.$api.notify.error(res.error);
                }
            }
            done();
        },
        // 查看信息
        viewContactInfo(record) {
            this.selectedRecord = record;
            this.showContactPopup = true;
        },
        // 查看成员信息
        async viewMemberInfo(record) {
            this.selectedRecord = record;
            const res = await this.$api.department.getDepartmentMember({
                departmentId: record.departmentId
            });
            if (res.success) {
                this.members = res.data;
                this.showMemberPopup = true;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        // 编辑成员信息
        showUpdateMember(member) {
            this.selectedMember = member;
            this.showUpdateMemberPopup = true;
        },
        async delMember() {
            // 处理移除成员的逻辑
            this.updateMemberLoading = true;
            const res = await this.$api.department.adminDelDepartmentMember({
                departmentId: this.selectedRecord.departmentId,
                userId: this.selectedMember.userId
            });
            this.updateMemberLoading = false;
            if (res.success) {
                this.$api.notify.success('删除成员成功！');
                this.members = this.members.filter((item) => item.userId !== this.selectedMember.userId);
                this.showUpdateMemberPopup = false;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        async setDirector() {
            // 处理设为主任的逻辑
            this.updateMemberLoading = true;
            const res = await this.$api.department.adminSetDirector({
                departmentId: this.selectedRecord.departmentId,
                userId: this.selectedMember.userId
            });
            this.updateMemberLoading = false;
            if (res.success) {
                this.$api.notify.success('设为主任成功！');
                this.members = this.members.map((item) => {
                    if (item.userId === this.selectedMember.userId) {
                        item.directorFlag = '1';
                    } else {
                        item.directorFlag = '0';
                    }
                    return item;
                });
                this.showUpdateMemberPopup = false;
                this.fetchData();
                this.showMemberPopup = false;
            } else {
                this.$api.notify.error(res.error);
            }
        }
    }
};
</script>
<style scoped></style>
